package com.base.cn.platform.os.service.user.loginLog;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.web.UserAgentUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.dao.user.loginLog.CusUserLoginLogDao;
import com.base.cn.platform.os.entity.user.count.UserLoginDeviceNum;
import com.base.cn.platform.os.entity.user.count.UserLoginNum;
import com.base.cn.platform.os.entity.user.loginLog.CusUserLoginLog;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 登录日志Biz
 * @author ll
 * @date 2018/6/1 9:56
 */
@Service
public class CusUserLoginLogBiz extends BaseBiz<CusUserLoginLog,CusUserLoginLogDao> {

    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private CusUserLoginLogDao cusUserLoginLogDao;

    /**
     * 分页搜索登录日志
     * @param userLoginLog
     * @param page
     * @return
     */
    public PageInfo<CusUserLoginLog> queryUserLoginLogList(CusUserLoginLog userLoginLog, Pagination page){
        StringBuilder  whereSql = new StringBuilder();
        String userIds = "";
        if(StringUtils.isNotEmpty(userLoginLog.getAccount())){
            whereSql.append(" nickname like concat('%','").append(userLoginLog.getAccount().trim()).append("','%') ");
            whereSql.append( " or email like concat('%','").append(userLoginLog.getAccount().trim()).append("','%')");
            whereSql.append(" or mobile like concat('%','").append(userLoginLog.getAccount().trim()).append("','%')");
            List<CusUser> userList = cusUserBiz.find(whereSql.toString(),null,null);
            if(!ObjectUtils.isNotEmpty(userList)){
                return null;
            }
            userIds = userList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
            userLoginLog.setUserIds(userIds);
        }
        String _whereSql = whereSql(userLoginLog);
        PageInfo<CusUserLoginLog> userLoginLogList = this.findPage(_whereSql,page,null);
        return userLoginLogList;
    }

    /**
     * 获取登录日志Sql
     * @param userLoginLog
     * @return
     */
    public String whereSql(CusUserLoginLog userLoginLog){
        StringBuilder whereSql = new StringBuilder(" 1=1");
        if(DataUtil.idIsNotNull(userLoginLog.getUserId())){
            whereSql.append(" and userId=").append(userLoginLog.getUserId());
        }
        if(StringUtils.isNotEmpty(userLoginLog.getUserIds())){
            whereSql.append(" and userId in (").append(userLoginLog.getUserIds()).append(")");
        }
        if(userLoginLog.getStartDate()!=null){
            whereSql.append(" and createTime >= '").append( DateUtils.format(userLoginLog.getStartDate(),"yyyy-MM-dd HH:mm:ss")).append("'");
        }
        if(userLoginLog.getEndDate()!=null){
            whereSql.append(" and createTime <= '").append( DateUtils.format(userLoginLog.getEndDate(),"yyyy-MM-dd HH:mm:ss")).append("'");
        }
        whereSql.append(" order by createTime desc");
        return whereSql.toString();
    }

    /**
     * 设置登录日志数据中的用户信息
     * @param userLoginLogList 日志列表
     */
    public void setUserLoginLogUser(List<CusUserLoginLog> userLoginLogList){
        if(ObjectUtils.isNotEmpty(userLoginLogList)){
            String userIds = userLoginLogList.stream().map(e->e.getUserId().toString()).collect(Collectors.joining(","));
            List<CusUser> userList = cusUserBiz.queryUserByIds(userIds,false,false,false,false,false,false,false);
            if(ObjectUtils.isNotEmpty(userList)){
                Map<BigDecimal,CusUser> userMap = userList.stream().collect(Collectors.toMap(CusUser::getId, e->e));
                for(CusUserLoginLog userLoginLog : userLoginLogList){
                    userLoginLog.setUser(userMap.get(userLoginLog.getUserId()));
                }
            }
        }
    }

    /**
     * 添加学员登录日志
     * @param request HttpServletRequest
     * @param userId 用户ID
     * @param loginFrom 登录来源
     */
    @Async
    public void saveUserLoginLog(HttpServletRequest request, BigDecimal userId, String loginFrom)throws IOException {
       /* List<String> list = WebUtils.getIpToAddress(request);
        String address = null;
        if(ObjectUtils.isNotEmpty(list)){
            address = list.stream().map(e->e).collect(Collectors.joining(" "));
        }*/
        //添加登录日志
        CusUserLoginLog userLoginLog = new CusUserLoginLog();
        userLoginLog.setUserId(userId);
        userLoginLog.setLoginIp(WebUtils.getIpAddr(request));
        userLoginLog.setLoginFrom(loginFrom);
        //userLoginLog.setAddress(address);
        UserAgentUtil userAgentUtil =new UserAgentUtil(request);
        String userAgent =  userAgentUtil.getBrowserName();
        String osName = userAgentUtil.getOSName();
        if (StringUtils.isNotEmpty(userAgent)&&StringUtils.isNotEmpty(osName)) {
            userLoginLog.setUserAgent(userAgent);// 浏览器
            userLoginLog.setOsName(osName);// 操作系统
        }
        this.save(userLoginLog);
    }

    /**
     * 查询用户登录天数
     * @param userId 用户ID
     * @return 登录天数
     */
    public int queryUserLoginDayNum(BigDecimal userId){
        return cusUserLoginLogDao.queryUserLoginDayNum(CusUserLoginLog.class,userId);
    }

    /**
     * 用户登录设备统计量
     * @return 统计对象
     */
    public UserLoginDeviceNum queryUserLoginDeviceNum(){
        return cusUserLoginLogDao.queryUserLoginDeviceNum(CusUserLoginLog.class);
    }

    /**
     * 查询活跃用户数量
     * @return 数量
     */
    public Integer queryActiveUserNum(){
        return cusUserLoginLogDao.queryActiveUserNum(CusUserLoginLog.class);
    }

    /**
     * 查询某一天平台用户24小时内每个小时的登录量
     * @param dateTime 时间
     * @return 统计数据列表
     */
    public List<UserLoginNum> queryUserLoginDayTimeNum(String dateTime){
        return cusUserLoginLogDao.queryUserLoginDayTimeNum(CusUserLoginLog.class,dateTime);
    }

    /**
     * 查询某一天平台登录量
     * @param map 时间
     * @return 统计数据列表
     */
    public List<Map<String,Object>> queryUserLoginTimeNum(Map<String,Object> map){

        if(StringUtils.isEmpty(map.get("begTime"))&&StringUtils.isEmpty(map.get("endTime"))){
            map.put("begTime",DateUtils.format(new Date(),"yyyy-MM-dd"));
            map.put("endTime",DateUtils.format(new Date(),"yyyy-MM-dd"));
        }
        return cusUserLoginLogDao.queryUserLoginTimeNum(CusUserLoginLog.class,map);
    }
}
